package edu.seu.mart.service.impl;

import edu.seu.mart.dao.ISellerDao;
import edu.seu.mart.entity.Pager;
import edu.seu.mart.model.Admin;
import edu.seu.mart.model.MartException;
import edu.seu.mart.model.Seller;
import edu.seu.mart.service.ISellerService;
import edu.seu.mart.utils.SecurityUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.security.NoSuchAlgorithmException;

/**
 * Created by asus on 2015/3/10.
 */
@Service
public class SellerService implements ISellerService {

    @Resource
    private ISellerDao sellerDao;


    @Override
    public Seller login(String username, String password)
    {
        Seller seller = sellerDao.loadByUsername(username);
        if (seller == null) throw new MartException("用户名或者密码不正确");
        try {
            if (!SecurityUtil.md5(username, password).equals(seller.getPassword())) {
                throw new MartException("用户名或者密码不正确");
            }
        } catch (NoSuchAlgorithmException e) {
            throw new MartException("密码加密失败:" + e.getMessage());
        }
        return seller;
    }

    @Override
    public Pager<Seller> findUser(String order) {
        return sellerDao.findUser(order);
    }

    @Override
    public void delete(int id) {
        sellerDao.delete(id);
    }

    @Override
    public void updateStatus(int id) {
        Seller u = sellerDao.load(id);
        if(u == null) throw new MartException("修改状态的商家不存在");
        if(u.getStatus() == 0) u.setStatus(1);
        else u.setStatus(0);
        sellerDao.update(u);
    }

    @Override
    public void deleteChecked(String[] ids) {
        try {
            for (String id : ids) {
                sellerDao.delete(Integer.valueOf(id));
            }
        } catch (Exception e) {
            throw new MartException("选中的用户删除失败");
        }
    }

    @Override
    public Pager<Seller> findSeller(String name) {
        return sellerDao.findSeller(name);
    }

    @Override
    public Seller load(int id) {
        return sellerDao.load(id);
    }

    @Override
    public void updateMoney(int id, double mondy) {
        Seller seller = sellerDao.load(id);
        if (seller != null) {
            seller.setMoney(mondy);
            sellerDao.update(seller);
        }
    }
}
